package com.morty.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class RedissonConfig {

    @Autowired
    private RedisConfigProperties redisConfigProperties;

    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient(){
        Config config = new Config();
        if(redisConfigProperties.getHost() != null) {
            config.useSingleServer().setAddress("redis://" + redisConfigProperties.getHost() + ":" + redisConfigProperties.getPort())
                    .setPassword(redisConfigProperties.getPassword()).setDatabase(redisConfigProperties.getDatabase());
        }else if(redisConfigProperties.getCluster().getNodes() != null && redisConfigProperties.getCluster().getNodes().size()>0){
            List<String> clusterNodes = new ArrayList<>();
            for (String clusterNode : redisConfigProperties.getCluster().getNodes()) {
                clusterNodes.add("redis://" + clusterNode);
            }
            ClusterServersConfig clusterServersConfig = config.useClusterServers()
                    .addNodeAddress(clusterNodes.toArray(new String[clusterNodes.size()]));
            clusterServersConfig.setPassword(redisConfigProperties.getPassword());//设置密码
        }
        return Redisson.create(config);
    }
}
